package com.ocm.warehouse.mqListener;

import com.rabbitmq.client.Channel;
import com.ocm.core.log.exception.ServiceException;
import com.ocm.core.tool.api.R;
import com.ocm.mq.annotation.RabbitAutoAck;
import com.ocm.order.feign.IOrderClient;
import com.ocm.warehouse.service.IStockService;
import com.ocm.warehouse.to.StockUnlockTO;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.ocm.common.constant.OrderStatusConstant.ORDER_STATUS_SHUTDOWN;

/**
 * @Author hqy
 * @Date 31/01/2022
 * @Description
 */
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

	@Resource
	private IStockService stockService;

	@Resource
	private IOrderClient orderClient;

	/**
	 * 自解锁库存
	 * @param orderId
	 * @param channel
	 * @param message
	 */
	@RabbitAutoAck
	@RabbitHandler
	public void stockLockListen(Long orderId, Channel channel, Message message){

		R<Integer> res = orderClient.getStatusById(orderId);
		if(!res.isSuccess()){
			throw new ServiceException(res.getMsg());
		}

		if(res.getData()==null||res.getData()==ORDER_STATUS_SHUTDOWN){
			//根据orderId 解锁库存
			//没有订单 证明创建订单失败 需要解锁库存
			stockService.stockUnlock(orderId);
		}
	}

	/**
	 * 主动解锁库存
	 * @param
	 * @param channel
	 * @param message
	 */
	@RabbitAutoAck
	@RabbitHandler
	public void stockLockListen(StockUnlockTO stockUnlockTO, Channel channel, Message message){
		//根据orderId 解锁库存
		stockService.stockUnlock(stockUnlockTO.getOrderId());
	}

}
